package cn.school.controller.student;

import cn.school.classManage.service.SchoolClassService;
import cn.school.classManage.vo.SchoolClassVO;
import cn.school.common.api.CommonPage;
import cn.school.common.api.CommonResult;
import cn.school.stu.evaluation.entity.StuEvaData;
import cn.school.stu.evaluation.vo.StuEvaDataExportVO;
import cn.school.student.entity.ExamInfoChartLine;
import cn.school.student.entity.StudentExamInfo;
import cn.school.student.service.ExamInfoService;
import cn.school.student.vo.ExamInfoVO;
import cn.school.sys.entity.SysDictDetail;
import cn.school.sys.service.SysDictDetailService;
import com.alibaba.excel.EasyExcel;

import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.WriteWorkbook;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.sl.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Row;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@Api(tags = "exam => 考试管理")
@RequestMapping("/exam/info")
public class ExamInfoController {

    @Resource
    private ExamInfoService examInfoService;

    @Resource
    private SysDictDetailService sysDictDetailService;

    @ApiOperation("分页查询列表")
    @PostMapping("/pageList")
//    @PreAuthorize("@ss.hasPermi('exam:info:list')")
    public CommonResult<CommonPage<ExamInfoVO>> findExamInfoPageList(@RequestBody ExamInfoVO examInfoVO){
        IPage<ExamInfoVO> pageList = examInfoService.findExamInfoPageList(examInfoVO);
        return CommonResult.success(CommonPage.restPage(pageList));
    }

    @ApiOperation("新增or修改考试信息")
    @PostMapping("/edit")
//    @PreAuthorize("@ss.hasPermi('exam:info:edit')")
    public CommonResult<CommonPage<ExamInfoVO>> addOrUpdateExamInfo(@RequestBody ExamInfoVO examInfoVO){
        int num = examInfoService.addOrUpdateExamInfo(examInfoVO);
        if(num>0) return CommonResult.success();
        return CommonResult.failed();
    }

    @ApiOperation("根据ID删除考试信息")
    @PostMapping("/delete")
//    @PreAuthorize("@ss.hasPermi('exam:info:delete')")
    public CommonResult<CommonPage<ExamInfoVO>> deleteExamInfoById(@RequestBody ExamInfoVO examInfoVO){
        int num = examInfoService.deleteExamInfoById(String.valueOf(examInfoVO.getId()));
        if(num>0) return CommonResult.success();
        return CommonResult.failed();
    }

    @ApiOperation("批量删除考试信息")
    @PostMapping("/deleteBatch")
//    @PreAuthorize("@ss.hasPermi('exam:info:deleteBatch')")
    public CommonResult<Integer> deleteBatchExamInfo(@RequestBody List<ExamInfoVO> list){
        int num = examInfoService.deleteBatchExamInfo(list);
        if(num>0) return CommonResult.success();
        return CommonResult.failed();
    }

    @ApiOperation("批量修改考试信息状态")
    @PostMapping("/updateBatch")
//    @PreAuthorize("@ss.hasPermi('exam:info:deleteBatch')")
    public CommonResult<Integer> updateBatchExamInfo(@RequestBody List<ExamInfoVO> list){
        int num = examInfoService.updateBatchExamInfo(list);
        if(num>0) return CommonResult.success();
        return CommonResult.failed();
    }
    
    @ApiOperation("通过学生id查询学生所有成绩")
    @GetMapping("/getGradesByStudentId/{studentId}")
    public CommonResult<List<StudentExamInfo>> getGradesByStudentId(@PathVariable String studentId) {
        List<StudentExamInfo> examInfos = examInfoService.getGradesByStudentId(studentId);
        return CommonResult.success(examInfos);
    }
    
    @ApiOperation("查询学生科目成绩走势图")
    @GetMapping("/getGradesLineChart/{studentId}")
    public CommonResult<List<ExamInfoChartLine>> getGradesLineChart(@PathVariable String studentId) {
        List<ExamInfoChartLine> result = examInfoService.getGradesLineChart(studentId);
        return CommonResult.success(result);
    }

    @Resource
    SchoolClassService schoolClassService;
    @ApiOperation("导出考试信息模板")
    @PostMapping("/exportTemplate")
    public CommonResult<List<ExamInfoChartLine>> importTemplate(HttpServletResponse response,@RequestBody ExamInfoVO vo) throws IOException {
        List<StuEvaDataExportVO> allList = new ArrayList<>();
        //查询出课程名字
        List<SysDictDetail> dictList = sysDictDetailService.getDictLable("course_type",vo.getCurriculumTypes());
        //查询班级名称
        SchoolClassVO schoolClassVO = schoolClassService.findClassInfoByClassId(Long.valueOf(vo.getClassId()));
        EasyExcel.write(response.getOutputStream(), null).head(getHeader(dictList,schoolClassVO.getClassName(),vo)).sheet("考试成绩录入模板").doWrite(allList);
        return CommonResult.success();
    }

    @ApiOperation("导入数据")
    @PostMapping("/import")
    public CommonResult<String> importExcel(HttpServletRequest request) throws IOException, ServletException {

        Part file = request.getPart("file");
        ExamInfoVO vo = new ExamInfoVO();
        vo.setExamBeginTime(request.getParameter("examBeginTime"));
        vo.setExamEndTime(request.getParameter("examEndTime"));
        String result = examInfoService.importExcel(file.getInputStream(),vo);

//        String result = examInfoService.importExcel(request.getInputStream(),null);
        return CommonResult.success(result);
    }

//    @ApiOperation("导入数据")
//    @PostMapping("/import")
//    public CommonResult<String> importExcel(@RequestParam("file") MultipartFile multipartFile,@RequestBody ExamInfoVO vo) throws IOException {
//        String result = examInfoService.importExcel(multipartFile.getInputStream(),vo);
//        return CommonResult.success(result);
//    }
    private List<List<String>> getHeader(List<SysDictDetail> dictList,String className,ExamInfoVO vo){
        List<List<String>> handList = new ArrayList<>();
        List<String> oneList = new ArrayList<>();
        oneList.add("考试名称");
        oneList.add("考试班级");
        oneList.add("学生姓名");
        oneList.add("学生姓名");
        handList.add(oneList);

        List<String> autoList = null;
        List<SysDictDetail> totleRow = new ArrayList<>();
        for (SysDictDetail sysDictDetail : dictList) {
            totleRow.add(sysDictDetail);
            totleRow.add(sysDictDetail);
        }
        for (int i=0;i<totleRow.size();i++) {
            autoList = new ArrayList<>();
            SysDictDetail sysDictDetail = totleRow.get(i);
            autoList.add(vo.getExamName());
            autoList.add(className);
            autoList.add(sysDictDetail.getDictLabel());
            if(i%2==0){
                autoList.add("分数");
            }else{
                autoList.add("是否通过");
            }
            handList.add(autoList);

        }


        return handList;
    }
}
